<template>
	<div class="cascader">
		<input type="text" class="form-control cascader-input" readonly="readonly" placeholder="请选择"
			   data-togger="dropdown" :data-target="thisId" :value="val"/>
		<a @click="clearSelect" v-show="clearIcon"><icon class="fa-times pull-right cascader-remove-icon"></icon></a>
		<drop-down :id="thisId">
			<cascade-panel :data="data" ></cascade-panel>
		</drop-down>
	</div>
</template>

<script>
	import DropDown from '../menu/DropDown.vue';
	import CascadePanel from './CascadePanel.vue';
	import Icon from '../widget/Icon.vue';
	import Emitter from './emitter';
	export default {
		name: 'CascadeSelector',
		mixins: [Emitter],
		data () {
			return {
				thisId: this.id,
				val: '',
				tempResult: '',
				clearIcon: false
			};
		},
		props: {
			id: {type: String, default: 'null'},
			data: {type: Array, required: true},
			loadData: {type: Function}
		},
		methods: {
			checkId () {
				if (this.thisId === 'null') {
					this.thisId = 'dropDown_' + Math.floor(Math.random() * 100000000);
				}
			},
			updateResult (result) {
				this.tempResult = result;
			},
			clearSelect () {
				if (this.disabled) return false;
				this.tempResult = [];
				this.broadcast('CascadePanel', 'on-clear');
			}
		},
		watch: {
			tempResult: function (newVal) {
				if (newVal && newVal.length) {
					let backUp = '';
					for (let key in newVal) {
						backUp += newVal[key].label + '=>';
					}
					backUp = backUp.substring(0, backUp.lastIndexOf('=>'));
					this.val = backUp;
					this.clearIcon = true;
				} else {
					this.val = '';
					this.clearIcon = false;
				}
				this.$emit('input', newVal);
			}
		},
		components: {
			DropDown,
			CascadePanel,
			Icon
		},
		mounted () {
			this.checkId();
			this.$on('on-select-end', () => {
				this.$children[1].hide();
			});
		}
	};
</script>
